package cn.ad.server.job.adapter.persistence.job;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Repository;

import cn.ad.server.job.adapter.dbaccess.AssembledCachedDataContainer;
import cn.ad.server.job.adapter.dbaccess.DbDataContainer;
import cn.ad.server.domain.ad.AdMaterial;
import cn.ad.server.domain.ad.AdMaterialGroup;
import cn.ad.server.domain.ad.AdTemplateSpec;
import cn.ad.server.domain.ad.AppClass;
import cn.ad.server.domain.ad.Creative;
import cn.ad.server.domain.ad.InteractionApp;
import cn.ad.server.domain.ad.InteractionRedirects;
import cn.ad.server.job.domain.job.AdMaterialGroupWarmUpService;
import cn.ad.server.domain.enumration.AdFormat;
@Repository
public class AdMaterialGroupWarmUpServant implements AdMaterialGroupWarmUpService {
	
	private static Logger logger = LoggerFactory.getLogger(AdMaterialGroupWarmUpServant.class);
	
	@Resource(name = "cacheRedisTemplate")
	private ValueOperations<String, AdMaterialGroup> adMaterialGroupValueOperations;
	
	@Resource(name = "cacheRedisTemplate")
	private RedisTemplate<String, String> redisTemplate;
	
	@Resource(name = "cacheRedisTemplate")
	private ValueOperations<String, Creative> creativeValueOperations;
	
	@Autowired
	private AssembledCachedDataContainer container;

	public void cachedAdMaterialGroup() {
		
		List<AdMaterialGroup> adMaterialGroups = DbDataContainer.getAdMaterialGroupAll();//所有
		if(adMaterialGroups==null){
			return;
		}
		ConcurrentHashMap<Long, CopyOnWriteArraySet<AdMaterialGroup>> mapper = container.getAdMaterialGroupsByCreativeIdMap();
//		ConcurrentHashMap<String, CopyOnWriteArraySet<AdMaterialGroup>> mapper2 = container.adMaterialGroupsByCreativeIdTamplatIdMap;//TODO 备用
		for (AdMaterialGroup admg:adMaterialGroups) {
			try {
				mapper.putIfAbsent(admg.getCreativeId(),new CopyOnWriteArraySet<AdMaterialGroup>());
				if (admg.getStatus() == 1) {
					attachSomething(admg);
					mapper.get(admg.getCreativeId()).add(admg);
					upToRedis(admg.getCreativeId(), admg, true);
				}else{
					mapper.get(admg.getCreativeId()).remove(admg);
					upToRedis(admg.getCreativeId(), admg, false);
				}
			} catch (Exception e) {
				if(admg!=null){						
					logger.error("错误：在获取AdMaterialGroup_id ="+admg.getId()+"数据时发生错误 \n 错误信息：", e);
				}
			}
		}
	}
	
	public void warmUpAdMaterialGroup() {
		cachedAdMaterialGroup();
		List<Creative> creativeAll = DbDataContainer.getCreativeAll();
		ConcurrentHashMap<Long, CopyOnWriteArraySet<AdMaterialGroup>> mapper = container.getAdMaterialGroupsByCreativeIdMap();
		for (Creative creative : creativeAll) { 
			if (creative.getStatus()==1) {
				if(creative.getAdFormat()==AdFormat.AD_NATIVE){		
					creative.setAdMaterialGroupSet(mapper.get(creative.getId()));
					creativeValueOperations.set(creative.toCacheKey(), creative);
				}
			}else{
				redisTemplate.delete(creative.toCacheKey());
			}
		}
	} 
	
	
	@Value("${cached.redisDebug:false}")
	private boolean redisDebug;
	
	void upToRedis(Long cId,AdMaterialGroup adm,boolean operatorFlg){
		if(!redisDebug){
			return;
		}
		String key = "AdMaterialGroupsByCreativeId:"+cId+":"+adm.getId();
		if(operatorFlg){			
			adMaterialGroupValueOperations.set(key, adm);
			adMaterialGroupValueOperations.set(adm.toCacheKey(), adm);
		}else{
			redisTemplate.delete(key);
			redisTemplate.delete(adm.toCacheKey());
		}
	}

	/**
	 * 附上 AdMaterial AdTemplateSpec InteractionRedirects InteractionApp AppClass 对象。
	 * @param admg
	 * @return
	 */
	private AdMaterialGroup attachSomething(AdMaterialGroup admg) {
		
		if(admg==null){
			return null;
		}
		AdMaterialGroup adMaterialGroup = admg;
		AdMaterial adMaterial = adMaterialGroup.getAdMaterial();
		if (adMaterial != null) {
			adMaterial = DbDataContainer.getAdMaterial(adMaterial.getId());
			adMaterialGroup.setAdMaterial(adMaterial);
		} else {
			adMaterialGroup.setAdMaterial(null);
		}

		AdTemplateSpec adTemplateSpec = adMaterialGroup.getAdTemplateSpec();
		if (adTemplateSpec != null) {
			adTemplateSpec = DbDataContainer.getAdTemplateSpec(adTemplateSpec.getId());
			adMaterialGroup.setAdTemplateSpec(adTemplateSpec);
		} else {
			adMaterialGroup.setAdTemplateSpec(null);
		}

		// 0 无交互 1 跳转 2 APP下载 3
		if (adMaterialGroup.getInteractionType() == 1) {
			InteractionRedirects interactionRedirect = DbDataContainer.getInteractionRedirect(adMaterialGroup.getInteractionId());
			adMaterialGroup.setInteractionRedirects(interactionRedirect);
		} else if (adMaterialGroup.getInteractionType() == 2) {
			InteractionApp interactionApp = DbDataContainer.getInteractionApp(adMaterialGroup.getInteractionId());
			if (interactionApp != null) {
				// 默认取两级
				AppClass appClass = DbDataContainer.getAppClass(interactionApp.getClassesId());

				interactionApp.setAppClass(appClass);
				if (appClass != null && appClass.getParentId() != 0) {
					AppClass parentAppClass = DbDataContainer.getAppClass(appClass.getParentId());

					appClass.setParentAppClass(parentAppClass);
				}
			}
			adMaterialGroup.setInteractionApp(interactionApp);
		}

		return adMaterialGroup;
	}
	

}
